//
//  MeAddressVC.m
//  Ginix
//
//  Created by 冯志强 on 2025/2/24.
//

#import "MeAddressVC.h"
#import "MeAddressCell.h"
#import "MeAddressNewVC.h"
@interface MeAddressVC ()<UITableViewDelegate,UITableViewDataSource,MGSwipeTableCellDelegate>
@property (nonatomic,strong) UITableView * listtView;
@property (nonatomic,strong) NSMutableArray * listArray;
@end

@implementation MeAddressVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setSubViewLayout];
    [self creatNavBtn];
}
-(void)setSubViewLayout{
    
    self.title = @"地址管理";
    self.navgationView.infoLabel.textColor = RDRGB(0x714933);
    
    [self.view addSubview:self.listtView];
    [_listtView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view).insets(UIEdgeInsetsMake(NavHeight + 10 * FMScaleX, 0, 20 * FMScaleX, 0));
    }];
}

-(void)creatNavBtn{
    
    UIButton * rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH - 64, StatusBar, 44, 44)];
    [self.navgationView addSubview:rightBtn];
    [rightBtn setImage:[UIImage imageNamed:@"Me_nav_rightBtn"] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightBtnAction) forControlEvents:UIControlEventTouchUpInside];
}
-(void)rightBtnAction{
    
    MeAddressNewVC * vc = [[MeAddressNewVC alloc]initWithType:0 model:[[AddressListModel alloc]init]];
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self requestData];
    
}

-(void)requestData{
    [self.listArray removeAllObjects];
    @WeakObj(self)
    [SPNetworkingIns GET:PORT(@"auth-center/api/log/selectAddressList") params:@{} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject, NSInteger code) {
        @StrongObj(self)
        NSArray * dataArr = [responseObject objectForKey:@"data"];
        if (dataArr.count) {
            for (NSDictionary * item in dataArr) {
                AddressListModel * model = [[AddressListModel alloc]init];
                model = [AddressListModel yy_modelWithDictionary:item];
                [self.listArray addObject:model];
            }
        }
        [self.listtView reloadData];
    } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
        
    }];
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return self.listArray.count ;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    
    return 110 * FMScaleX;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MeAddressCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MeAddressCell"];
    cell.delegate = self;
    AddressListModel * model = self.listArray[indexPath.row];
    if(model){
        [cell setInfoModel:model];
    }
    return cell;
}

-(nullable NSArray<UIView*>*) swipeTableCell:(nonnull MGSwipeTableCell*) cell swipeButtonsForDirection:(MGSwipeDirection)direction
                               swipeSettings:(nonnull MGSwipeSettings*) swipeSettings expansionSettings:(nonnull MGSwipeExpansionSettings*) expansionSettings {
    
    swipeSettings.transition = MGSwipeTransitionBorder; // 滑出动画

    if (direction == MGSwipeDirectionRightToLeft) {
        
        // 扩张之后出发button的下标值
        expansionSettings.buttonIndex = 0;
        // 扩张填充单元格时是否弹回到其初始位置,如果为NO，则弹回到初始位置
        expansionSettings.fillOnTrigger = YES;
        // 尺寸比例阈值触发扩展按钮。 默认值1.5
        expansionSettings.threshold = 1.5;
        // 扩张单元格时的颜色
        expansionSettings.expansionColor = [UIColor redColor];
        // 扩张单元格时字体字体布局
        expansionSettings.expansionLayout = MGSwipeExpansionLayoutBorder;
        
        // 每一个button的宽度
        CGFloat padding = 25;
        @WeakObj(self)
        MGSwipeButton * edit = [MGSwipeButton buttonWithTitle:@"删除" backgroundColor:UIColor.redColor padding:padding callback:^BOOL(MGSwipeTableCell *sender) {
            @StrongObj(self)
            NSIndexPath *indexPath = [self.listtView indexPathForCell:sender];
            AddressListModel * model = self.listArray[indexPath.row];
            if (model) {
                [SPNetworkingIns GET:PORT(@"auth-center/api/log/deleteAddressListById") params:@{@"addressId":model.ID} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject, NSInteger code) {
                    FhudShowStr(@"删除成功")
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self requestData];
                    });
                } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                    
                }];
            }
            return YES;
        }];
        
        MGSwipeButton * delete = [MGSwipeButton buttonWithTitle:@"设为默认" backgroundColor:RDRGB(0xE8DFD4) padding:padding callback:^BOOL(MGSwipeTableCell *sender) {
                    
            NSIndexPath *indexPath = [self.listtView indexPathForCell:sender];
            AddressListModel * model = self.listArray[indexPath.row];
            if (model) {
                NSDictionary * params = @{@"name":model.name,@"phone":model.phone,@"province":model.province,@"city":model.city,@"district":model.district,@"street":model.district,@"detailAddress":model.detailAddress,@"isDefault":@(1),@"id":model.ID};
                [SPNetworkingIns POST:PORT(@"auth-center/api/log/updateAddressListById") params:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject, NSInteger code) {
                    FhudShowStr(@"修改成功");
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [self requestData];
                    });
                } fail:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
                    
                }];
            }
            
            return YES;
        }];
                
        return @[edit,delete];
    }
    return nil;
}

-(UITableView *)listtView{
    
    if (!_listtView) {
        _listtView = [[UITableView alloc]init];
        _listtView.delegate = self;
        _listtView.dataSource = self;
        _listtView.showsVerticalScrollIndicator = NO;
        _listtView.showsHorizontalScrollIndicator = NO;
        _listtView.backgroundColor = UIColor.clearColor;
        _listtView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listtView.bounces = NO;
        [_listtView registerClass:[MeAddressCell class] forCellReuseIdentifier:@"MeAddressCell"];
    }
    return _listtView;
}
-(NSMutableArray *)listArray{
    
    if(!_listArray){
        _listArray = [[NSMutableArray alloc]init];
    }
    return _listArray;
}
@end
